package cn.xnatural.demo;

import cn.xnatural.app.AppContext;
import cn.xnatural.app.Bean;
import cn.xnatural.app.ServerTpl;
import cn.xnatural.demo.entity.User;
import cn.xnatural.enet.event.EL;
import cn.xnatural.jpa.Repo;
import cn.xnatural.xnet.HChain;
import cn.xnatural.xnet.XNet;

@Bean
public class Main {
    static final AppContext app = new AppContext(); // 创建应用

    public static void main(String[] args) {
        app.start();
    }



    /**
     * 创建数据库操作
     */
    @Bean ServerTpl localRepo() {
        return new ServerTpl("localRepo") { //数据库 localRepo
            Repo repo;
            @EL(name = "sys.starting", async = true)
            void start() {
                repo = new Repo(attrs()).entities(
                        User.class
                ).init();
                exposeBean(repo, name);
                ep.fire(name + ".started");
            }

            @EL(name = "sys.stopping", async = true, order = 2f)
            void stop() { if (repo != null) repo.close(); }
        };
    }


    /**
     * 创建 web服务
     */
    @Bean ServerTpl xnet() {
        return new ServerTpl("xnet") { //添加http服务
            XNet xnet;

            @EL(name = "sys.starting", async = true, order = 1)
            void start() {
                xnet = new XNet(attrs(), exec(), app().scheduler());
                HChain chain = xnet.http().chain();
                app().beans().forEachRemaining(e -> chain.resolve(e.getValue())); // 解析所有对象中的路由
                xnet.start();
            }

            @EL(name = "sys.stopping")
            void stop() { if (xnet != null) xnet.close(); }
        };
    }
}
